
import * as constant from '../constant'

import request from '../request'

import { push } from 'connected-react-router'

//清空数据
export const unload = () => {
    return { type: constant.USER_UNLOAD }
}

//字段同步
export const userFieldUpdate = (key, value) => {
    return { type: constant.USER_REGIST_FIELD, key, value }
}

// 注册提交
export const registSubmit = ({ email, username, password }) => {
    return async (dispatch, getState) => {
        try {
            // 网络请求
            const result = await request.user.regist(email, username, password)
            // 成功 status 1
            console.log("result123", result);
            if (result.status === 1) {
                // 跳转Login ？
                // redux +  react-router
                dispatch(push('/login')) //触发跳转
            } else {// 失败 status 0
                dispatch({ type: constant.USER_REGIST_RESULT, result })
            }
        } catch (error) { // 错误
            console.log(error);
            dispatch({ type: constant.USER_REGIST_RESULT, result: { message: error.message, errors: error.errors } })
        }

    }
}
// 登录提交
export const loginSubmit = (email, password) => {
    return async (dispatch, getState) => {
        try {
            // 网络请求
            const result = await request.user.login(email, password)
            console.log("login---", result);
           
            dispatch({ type: constant.USER_LOGIN_RESULT, result })


        } catch (error) { // 错误
            console.log(error);
            dispatch({ type: constant.USER_REGIST_RESULT, result: { status: 0, message: error.message, errors: error.errors } })
        }

    }
}

//用户登录字段同步
export const userSyncResult = (user) => {
    console.log("action:", user);
    return { type: constant.USER_SYNC_RESULT, result: user }
}

// 更新提交
export const updataSubmit = (user) => {
    return async (dispatch) => {
        try {
            // 网络请求
            console.log('updata action',user);
           
            const result = await request.user.update(user)
            console.log('updata action',result);
       

            dispatch({ type: constant.USER_UPDATA_RESULT, result })

        } catch (error) { // 错误
            // console.log(error);
            dispatch({ type: constant.USER_UPDATA_RESULT, result: { status: 0, message: error.message, errors: error.errors } })
        }

    }
}

export const logout=()=>{
    return {type:constant.USER_SETTING_LOGOUT}
}

